package com.wuuxiang.i5xforyou.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wuuxiang.i5xforyou.common.consts.Consts;
import com.wuuxiang.i5xforyou.common.domain.ResultMsg;
import com.wuuxiang.i5xforyou.common.domain.Results;
import com.wuuxiang.i5xforyou.common.service.impl.BaseServiceImpl;
import com.wuuxiang.i5xforyou.service.CommonService;
import com.wuuxiang.i5xforyou.service.MemberCardsService;
import com.wuuxiang.i5xforyou.utils.DateUtil;
import com.wuuxiang.i5xforyou.utils.HttpUtil;
import com.wuuxiang.i5xforyou.vo.CrmCard;
import com.wuuxiang.i5xforyou.vo.CrmCards;
import com.wuuxiang.i5xforyou.vo.CrmVersion;

@Service("memberCardsService")
public class MemberCardsServiceImpl extends BaseServiceImpl implements MemberCardsService {

	@Autowired
	private CommonService commonService;
	
	@Override
	public ResultMsg joinMemberCards(String nickName, String sex, String verifyCode, String mpId, String openId, String phoneNo, String marketActivityId) {
		Boolean firstOauth = true;
		ResultMsg resultMsg = new ResultMsg();
		
		String gcId = commonService.getGcIdByMpId(mpId);
		if(gcId==null) {
			log.error("用户认证失败(joinMemberCards):云端微信业务未绑定门店");
			resultMsg.setState(Results.ERROR);
			resultMsg.setMsg("用户认证失败(joinMemberCards):云端微信业务未绑定门店");
			resultMsg.setException(new Exception("用户认证失败(joinMemberCards):云端微信业务未绑定门店"));
	        return resultMsg;
    	}
		//获取crm版本
    	CrmVersion crmVersion = commonService.getCrmVersion(mpId);
    	if (CrmVersion.CRM7 == crmVersion) {
    		String oldBit = "GREGORIAN";
        	sex = StringUtils.isBlank(sex)||"1".equals(sex.trim())?"MALE":"FEMALE"; //12210男12220女 1男2女
    		String url = Consts.CRM7_WEBSERVICE_URL + getCrm7UrlPrefix() + "crm/member/register";
			JSONObject params = new JSONObject();

			params.put("mpId", mpId);
			params.put("openId", openId);
			JSONObject dataObject = new JSONObject();
			if(StringUtils.isNotBlank(phoneNo)) {
				dataObject.put("mobile", phoneNo);
			}
			dataObject.put("appType", "WECHAT");
			dataObject.put("sex", sex);
			if(StringUtils.isNotEmpty(oldBit)) {
				dataObject.put("birthdayType", oldBit);
			}
			if(StringUtils.isNotEmpty(nickName)) {
				Pattern p = Pattern.compile("^[0-9a-zA-Z\u4E00-\u9FA5]{0,10}$");
				Matcher m = p.matcher(nickName);
				if (m.matches()) {
					//符合crm名字规范的用户名才传给crm7
					dataObject.put("name", nickName);
				}
			}
			params.put("data", dataObject);
			try {
				JSONObject reJsObject = HttpUtil.doPostCrm7JSONObject(url, params);
				// 接口返回正常，进行数据解析
				if ("200".equals(reJsObject.getString("code"))) {
						//将接口返回内容转换为前端所需要的数据
						CrmCards crmCards = new CrmCards();
						List<CrmCard> crmCardInfo = new ArrayList<CrmCard>(0);

						JSONObject contentObject = reJsObject.getJSONObject("content");
						JSONObject memberObject = contentObject.getJSONObject("member");
						JSONArray cardsArray = contentObject.getJSONArray("card");
						for (int i = 0; i < cardsArray.size(); i++) {
							CrmCard crmCard = new CrmCard();

							JSONObject cardObject = cardsArray.getJSONObject(i);
							crmCard.setEmail(memberObject.getString("email"));
							crmCard.setName(memberObject.getString("name"));
							String rstSex =  memberObject.getString("sex");
							crmCard.setSex("0".equals(rstSex) ? "2" : rstSex);//"0":女，"1":男  转换为1:男，2：女
							if(memberObject.getDate("birthday")!=null) {
								crmCard.setBirthday(DateUtil.dt2s(memberObject.getDate("birthday"), DateUtil.YYYY_MM_DD));
							}
							crmCard.setShopname(memberObject.getString("companyName"));
							//多卡的门店name放到了card里面
							//crmCard.setSubshopname(memberObject.getString("shopName"));
							//默认显示公历生日
							crmCard.setOldBit("0");
							crmCard.setCardScore(cardObject.getString("balanceScore"));
							crmCard.setConsumeTimes(cardObject.getInteger("sumConsumeTimes"));
							crmCard.setCardNo(cardObject.getString("number"));
							crmCard.setKindName(cardObject.getString("cardTypeName"));
							crmCard.setCard_kind(cardObject.getString("cardTypeId"));
							String validateType = cardObject.getString("validateType");
							//有效时间类型为永久有效的卡显示失效时间为"2050-12-31"
							if(!StringUtils.equals(validateType, "1")) {
								crmCard.setValidBegin(cardObject.getString("validateBeginTime"));
								crmCard.setValidEnd(cardObject.getString("validateEndTime"));
							}else{
								crmCard.setValidBegin(cardObject.getString("createTime"));
								crmCard.setValidEnd("2050-12-31");
							}
							crmCard.setCardValidateTag(cardObject.getString("cardValidateTag"));

							crmCard.setBalanceTimes(cardObject.getString("balanceTimes"));
							crmCard.setRemarks(cardObject.getString("cardTypeNote"));
							crmCard.setAllChargeMoney(cardObject.getString("sumChargeMoney"));
							crmCard.setTicketCount(cardObject.getString("surplusCoupon"));;
							crmCard.setBalanceMoney(cardObject.getString("balanceMoney"));
							crmCard.setAllChargePerMoney(cardObject.getString("sumGiveMoney"));
							crmCard.setMobile(cardObject.getString("mobile"));
							//多卡的门店name放到了card里面
							crmCard.setSubshopname(cardObject.getString("saledShopName"));
							JSONObject cardFace = cardObject.getJSONObject("cardFace");
							if (cardFace != null && !cardFace.isEmpty()) {
								crmCard.setCardNo_X(cardFace.getString("cardNoX"));
								crmCard.setCardNo_Y(cardFace.getString("cardNoY"));
								crmCard.setCardType_X(cardFace.getString("cardTypeX"));
								crmCard.setCardType_Y(cardFace.getString("cardTypeY"));
								crmCard.setFontColor(cardFace.getString("colorCardNo"));
								crmCard.setCardTypeColor(cardFace.getString("colorCardTypeName"));
								crmCard.setMobileColor(cardFace.getString("colorMobile"));
								crmCard.setShopColor(cardFace.getString("colorShopName"));
								crmCard.setCardStyleImage(cardFace.getString("imgUrl"));
								crmCard.setCardNoShowFlg(cardFace.getInteger("isCardNo"));
								crmCard.setCardTypeShowFlg(cardFace.getInteger("isCardTypeName"));
								crmCard.setMobileShowFlg(cardFace.getInteger("isMobile"));
								crmCard.setShopNameShowFlg(cardFace.getInteger("isShopName"));
								crmCard.setMobile_X(cardFace.getString("mobileX"));
								crmCard.setMobile_Y(cardFace.getString("mobileY"));
								crmCard.setShopname_X(cardFace.getString("shopNameX"));
								crmCard.setShopname_Y(cardFace.getString("shopNameY"));
							}else{
								// 如果接口没有返回卡样信息，则设置默认卡样
								crmCard.setCardNo_X("209");
								crmCard.setCardNo_Y("109");
								crmCard.setCardType_X("11");
								crmCard.setCardType_Y("37");
								crmCard.setFontColor("#000000");
								crmCard.setCardTypeColor("#000000");
								crmCard.setMobileColor("#000000");
								crmCard.setShopColor("#000000");
								crmCard.setCardNoShowFlg(1);
								crmCard.setCardTypeShowFlg(1);
								crmCard.setMobileShowFlg(1);
								crmCard.setShopNameShowFlg(1);
								crmCard.setMobile_X("176");
								crmCard.setMobile_Y("136");
								crmCard.setShopname_X("11");
								crmCard.setShopname_Y("11");
							}

							crmCardInfo.add(crmCard);
						}
						crmCards.setCrmCardInfo(crmCardInfo);
						resultMsg.setMsg("尊敬的服务窗用户,初始密码为:111111,建议您到门店完善您的会员资料!");
						resultMsg.setMsgEntity(crmCards);
					    return resultMsg;
				} else {
					// 记录Cat.logError
					StringBuilder message = new StringBuilder("调用【注册会员】接口失败{url:").append(url).append(",data:").append(params.toString()).append("}");
					// Cat.logEvent("wechat/member/register", reJsObject.getString("code"), "Failure", message.toString());
					log.error(message+" 接口返回:"+reJsObject.toJSONString());
					resultMsg.setState(Results.ERROR);
					resultMsg.setMsg(reJsObject.getString("msg"));
					resultMsg.setException(new Exception(reJsObject.getString("msg")));
			        return resultMsg;
				}
			} catch (Exception e) {
				// 记录Cat.logError
				StringBuilder message = new StringBuilder("调用【注册会员】接口失败{url:").append(url).append(",params:").append(params.toString()).append("}");
				//Cat.logError(message.toString(), e);

				log.error("获取会员卡失败(joinMemberCards):" + e.toString() + ",url:" + url + ",firstOauth:" + firstOauth);
				resultMsg.setState(Results.ERROR);
				resultMsg.setException(new Exception(("获取会员卡失败(joinMemberCards):" + e.toString())));
				return resultMsg;
			}
    	} else if (CrmVersion.CRM6 == crmVersion) {
        	sex = StringUtils.isBlank(sex)?"":"1".equals(sex)?"12210":"12220"; //12210男12220女 1男2女
	    	JSONObject postData = new JSONObject();
	    	postData.put("mpId", mpId);
	    	// 请求来源.0:微信,1:支付宝 2:小程序
	    	postData.put("fromType", 2);
	    	postData.put("mobile", phoneNo);
	    	postData.put("sex", sex);
	    	postData.put("name", nickName);
	    	// 首次认证标识,传TRUE的情况下,如果CRM6有卡未绑定的话则进行绑卡,传FASLE的话有卡未绑定的也会在申请一张,小刘伟说的
	    	postData.put("firstFlag", firstOauth);
	    	postData.put("openId", openId);
			postData.put("gcId", gcId);
			if(StringUtils.isNotEmpty(marketActivityId)) {
				postData.put("marketActivityId", marketActivityId);
			}
	    	StringBuilder url = new StringBuilder(Consts.CLOUD_API_URL);
	    	url.append("rest/card/wxCommGetCard");
	    	url.trimToSize();
			try {
				CrmCards crmCards = HttpUtil.doPostObject(url.toString(), postData.toJSONString(), CrmCards.class);
				if (crmCards != null && crmCards.getCrmCardInfo() != null) {
					for (CrmCard crmCard : crmCards.getCrmCardInfo()) {
						//"12220":女，"12210":男  转换为1:男，2：女
						if ("12220".equals(crmCard.getSex()) ) {
							crmCard.setSex("2");
						} else if ("12210".equals(crmCard.getSex())) {
							crmCard.setSex("1");
						} else {
							crmCard.setSex("0");
						}
					}
				}
				if (crmCards.getV_error_code() == 0){
				     resultMsg.setState(Results.SUCCESS);
				     resultMsg.setMsg("尊敬的服务窗用户,初始密码为:111111,建议您到门店完善您的会员资料!");
				     resultMsg.setMsgEntity(crmCards);
				     return resultMsg;
				}
				// 记录Cat.logEvent
				// Cat.logEvent("CRM_WEBSERVICE_URL.CommGetCard", String.valueOf(crmCards.getV_error_code()), "Failure", "{URL:[" + url + "]" + ",firstOauth:[" + firstOauth + "]" + ",PhoDinerVo:[" + pv.toString() + "]}");

		        log.error("获取会员卡失败(joinMemberCards):" + crmCards.getV_error_msg() + ",url:" + url + ",firstOauth:" + firstOauth);
		        resultMsg.setState(Results.ERROR);
		        resultMsg.setException(new Exception(crmCards.getV_error_msg() +"，请尽快联系商家！"));;
		        return resultMsg;
			} catch (Exception e) {
				// 记录Cat.logError
				StringBuilder message = new StringBuilder("获取会员卡失败{url:").append(url).append(",firstOauth:").append(firstOauth);
		    	//Cat.logError(message.toString(), e);

				log.error("获取会员卡失败(joinMemberCards):" + e.toString() + ",url:" + url + ",firstOauth:" + firstOauth);
				resultMsg.setState(Results.ERROR);
				resultMsg.setException(new Exception("获取会员卡失败(joinMemberCards):" + e.toString()));
				return resultMsg;
			}
    	}
    	log.error("获取用户卡信息异常" + ",获取CRM版本号UNKNOW");
		resultMsg.setState(Results.ERROR);
		resultMsg.setException(new Exception("获取用户卡信息异常" + ",获取CRM版本号UNKNOW"));
		return resultMsg;
	}

	@Override
	public CrmCard getPrimaryCard(String mpId, String openId) {
		//获取crm版本
    	CrmVersion crmVersion = commonService.getCrmVersion(mpId);
		if (crmVersion == CrmVersion.CRM7) {
			//CRM7调用接口获取会员卡信息
			try {
				JSONObject outputJson = getCrm7CardInfo(mpId, openId);
				int code = outputJson.getIntValue("code");
				if (code == 200) {//成功
					//返回内容
					JSONArray contents = outputJson.getJSONArray("content");
					if (contents != null && !contents.isEmpty()) {
						for (int i = 0; i < contents.size(); i++) {
							JSONObject content = contents.getJSONObject(i);
							if (content.getIntValue("isDefault") == 1) {
								//返回主卡
								CrmCard crmCard = new CrmCard();
								crmCard.setMobile(content.getString("mobile"));
								crmCard.setCardNo(content.getString("number"));
								crmCard.setKindName(content.getString("cardTypeName"));//卡类型名
								crmCard.setCard_kind(content.getString("cardTypeId"));//卡类型id
								return crmCard;
							}
						}
					}
				}
				return null;
			} catch (Exception e) {
				log.error("获取主卡对象失败(getPrimaryCard)" + "," + e.toString());
				return null;
			}

		} else if (crmVersion == CrmVersion.CRM6)  {
//			UserAgent userAgent = getNavigatorUserAgent();

			StringBuilder url = new StringBuilder(Consts.CRM6_WEBSERVICE_URL);
			url.append("WeiXinGetCardInfo");
			url.append("&weixinPlatID=").append(mpId);
			url.append("&weixinID=").append(openId);
//			if (userAgent.isWechat()){
//				url.append("&fromType=0");
//			}
//			if (userAgent.isAlipay()){
//				url.append("&fromType=1");
//			}
			url.append("&fromType=2"); //TODO 小程序是2？
			url.trimToSize();
			try {
				JSONObject jsonCardObj = HttpUtil.doGetJSONObject(url.toString());
				int v_card_error_code = jsonCardObj.getIntValue("v_error_code");
				if (v_card_error_code == 0) {
					JSONObject primaryCardInfo = jsonCardObj.getJSONObject("primaryCardInfo");
					CrmCard crmCard = new CrmCard();
					crmCard.setMobile(primaryCardInfo.getString("mobile"));
					crmCard.setCardNo(primaryCardInfo.getString("cardNo"));
					crmCard.setKindName(primaryCardInfo.getString("cardKindName"));//卡类型名
					crmCard.setCard_kind(primaryCardInfo.getString("cardKindId"));//卡类型id
					crmCard.setNation(primaryCardInfo.getString("nation"));
					crmCard.setSex(primaryCardInfo.getString("sex"));
					crmCard.setInterest(primaryCardInfo.getString("interest"));
					crmCard.setCustomer_request(primaryCardInfo.getString("customerRequest"));
					return crmCard;
				}
				return null;
			} catch (Exception e) {
				log.error("获取主卡对象失败(getPrimaryCard),url:" + url + "," + e.toString());
				return null;
			}
		}
		return null;
	}
	
	/**
	 * getCrm7CardInfo
	 * @Description: 调用crm7的接口获取会员卡信息
	 * @author Mobile Web Group-lff
	 * @date 2017年1月12日 上午10:35:59
	 *
	 * @param mpId
	 * @param openId
	 * @return JSONObject
	 * @throws Exception
	 */
	private JSONObject getCrm7CardInfo(String mpId, String openId) throws Exception {
		String url = Consts.CRM7_WEBSERVICE_URL + getCrm7UrlPrefix() + "crm/card/single";
		JSONObject inputParams = new JSONObject();

		inputParams.put("mpId", mpId);
		inputParams.put("openId", openId);
		//调用接口获取会员卡信息
		return HttpUtil.doPostCrm7JSONObject(url, inputParams);
	}
}
